import Layer from '../core/Layer';
import Sector from '../base/Sector';
import MultiLine from '../base/MultiLine';
import Point from '../core/Point';
import Color from '../core/Color';
import Text from '../base/Text';

export default class extends Layer {
    constructor(canvas, options) {
        super(canvas);
        this.width = options.width;
        this.data = options.data || [];
        this.angle = 360;
        this.labelColor = options.color || '#333333';
    }

    make() {
        this.childs.splice(0, this.childs.length);
        if(this.data.length === 0) {
            return;
        }

        let drawed = 0;
        for (let i = 0; i < this.data.length; i++) {
            let targetRadius = drawed + this.data[i].value;
            if (targetRadius > this.angle) {
                targetRadius = this.angle;
            }
            let sector = new Sector(this.canvas, {
                color: this.data[i].color,
                start: drawed / 180 * Math.PI,
                stop: targetRadius / 180 * Math.PI,
                radius: this.width / 2
            });
            sector.setPosition(this.position.x, this.position.y);
            this.addChild(sector);
            const centerAngle = (drawed + targetRadius) / 2;
            const sig = centerAngle > 90 && ((drawed + targetRadius) / 2) < 270;
            let centerX = this.position.x + Math.cos(centerAngle / 180  * Math.PI) * this.width / 2;
            let centerY = this.position.y - Math.sin(centerAngle / 180 * Math.PI) * this.width / 2;
            let centerX2 = this.position.x + Math.cos(centerAngle / 180 * Math.PI) * (this.width + 40) / 2;
            let centerY2 = this.position.y - Math.sin(centerAngle / 180 * Math.PI) * (this.width + 40) / 2;
            let centerX3 = centerX2 + (sig ? -1 : 1) * 20;
            let multiLine = new MultiLine(
                this.canvas,
                [
                    new Point(centerX, centerY),
                    new Point(centerX2, centerY2),
                    new Point(centerX3, centerY2)
                ]
            );
            multiLine.setColor(new Color(this.labelColor));
            multiLine.setLineWidth(2);
            this.addChild(multiLine);
            let txt = new Text(this.canvas, {
                text: `${this.data[i].label}${this.data[i].value}%`,
                color: this.labelColor,
                size: 20,
                font: 'Arial'
            });
            let txtLen = 0.518 * `${this.data[i].label}${this.data[i].value}%`.length * 20;
            txt.setPosition(centerX3 + (sig ? -1 : 0) * txtLen , centerY2);
            this.addChild(txt);

            if (drawed + this.data[i].value >= this.angle) {
                break;
            }
            drawed = targetRadius;
        }

    }

}
